from fastapi import FastAPI
from app.api.endpoints import simulation, callbacks
from app.core.config import settings
from app.services import service_manager
from app.services.platform_auth import platform_auth
from app.services.platform_subscribe import platform_subscribe
import logging

logger = logging.getLogger(__name__)

app = FastAPI(
    title="门禁控制系统",
    description="用于管理门禁的开关控制系统",
    version="1.0.0"
)

# 注册路由
app.include_router(simulation.router, prefix="/api/simulation", tags=["simulation"])
app.include_router(callbacks.router, prefix="/api", tags=["callbacks"])

@app.on_event("startup")
async def startup_event():
    """应用启动时的初始化"""
    try:
        logger.info("开始初始化服务...")
        logger.debug(f"当前配置: {settings.dict()}")
        
        # 首先初始化认证服务
        logger.info("初始化认证服务...")
        await platform_auth.initialize()
        
        # 然后初始化其他服务
        logger.info("初始化其他服务...")
        await service_manager.initialize(settings)
        
        logger.info("开始订阅平台事件...")
        # 订阅平台事件
        await platform_subscribe.subscribe_dahua_events([
            "AccessControl",  # 门禁事件
            "Face",          # 人脸识别事件
            "Alarm"          # 报警事件
        ])
        
        await platform_subscribe.subscribe_hikvision_events([
            "FACE_MATCH",     # 人脸比对事件
            "ACCESS_CONTROL", # 门禁事件
            "ALARM"          # 报警事件
        ])
        logger.info("应用初始化完成")
    except Exception as e:
        logger.error(f"应用初始化失败: {str(e)}")
        raise

@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时的清理"""
    # 取消订阅平台事件
    await platform_subscribe.unsubscribe_dahua_events([
        "AccessControl",
        "Face",
        "Alarm"
    ])
    
    await platform_subscribe.unsubscribe_hikvision_events([
        "FACE_MATCH",
        "ACCESS_CONTROL",
        "ALARM"
    ])
    
    # 关闭HTTP会话
    await platform_auth.close()

@app.get("/")
async def root():
    return {"message": "门禁控制系统API"}
